﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace MyMusicCollection.Model
{
	class TrackHandler
	{
		public Track GetTrack(AlbumTrack aAlbumTrack)
		{
			Track theTrack = new Track();

			theTrack.mArtist = aAlbumTrack.mArtist;
			theTrack.mAlbum = aAlbumTrack.mAlbum;
			theTrack.mTitle = aAlbumTrack.mTitle;
			theTrack.mDuration = aAlbumTrack.mDuration;

			LyricsWikiReader lwReader = new LyricsWikiReader();
			XmlTextReader xmlReader = lwReader.GetLyricsResponse(aAlbumTrack.mArtist, aAlbumTrack.mTitle);
			XmlDocument xmlDoc = new XmlDocument();

			if (xmlReader == null)
			{
				Console.WriteLine("Fel vid kopplingen till Discogs.");
				return null;
			}

			try
			{
				//Måste hoppa över vissa rader pga. mellanslag i responsen
				xmlReader.Read();
				xmlReader.Read();
				xmlReader.Read();
				xmlDoc.LoadXml(xmlReader.ReadOuterXml());
				xmlReader.Close();

				//Hämtar lyricsen
				if (xmlDoc.SelectSingleNode("LyricsResult/lyrics") != null)
				{
					theTrack.mLyrics = xmlDoc.SelectSingleNode("LyricsResult/lyrics").InnerText;
				}
				else
				{
					theTrack.mLyrics = "Sångtext ej tillgänglig.";
				}

				return theTrack;
			}
			catch (Exception e)
			{
				Console.WriteLine("Något gick fel med kopplingen till LyricsWiki.");
				xmlReader.Close();
				return null;
			}
		}
	}
}
